package com.kanche.bigbaby;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.util.Log;

import com.kanche.bigbaby.bean.ResponseMcSigninBean;
import com.kanche.bigbaby.collection.ImageUploadTaskQueue;
import com.kanche.bigbaby.collection.ImageUtils;
import com.kanche.bigbaby.collection.VehicleUploadTaskQueue;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.squareup.otto.Bus;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Created by Chenshao_Young on 15/5/15.
 */
public class BigBabyApplication extends Application {

    public  static boolean NeedRefresh_CollectionFrag = false;

    public long totalMemory;
    public static Context applicationContext;
    public static BigBabyApplication instance;

    private Bus bus;
    private ImageUploadTaskQueue queue;
    public void setQueue(ImageUploadTaskQueue queue) {
        this.queue = queue;
    }
    public ImageUploadTaskQueue getQueue() {
        return queue;
    }
    public Bus getBus() {
        return this.bus;
    }


    private VehicleUploadTaskQueue vehicleUploadTaskQueue;

    public void setVehicleUploadTaskQueue(VehicleUploadTaskQueue vehicleUploadTaskQueue) {
        this.vehicleUploadTaskQueue = vehicleUploadTaskQueue;
    }


    public VehicleUploadTaskQueue getVehicleUploadTaskQueue() {
        return vehicleUploadTaskQueue;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        totalMemory = getTotalMemory();


        applicationContext = this;
        instance = this;

        this.bus = new Bus();


        File cacheDir = StorageUtils.getCacheDirectory(this);

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
//                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
//                .diskCacheExtraOptions(480, 800, null)
//                .threadPoolSize(3) // default
//                .threadPriority(Thread.NORM_PRIORITY - 2) // default
//                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
//                .memoryCacheSize(2 * 1024 * 1024)
//                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiscCache(cacheDir)) // default
//                .diskCacheSize(500 * 1024 * 1024)
//                .diskCacheFileCount(100)
                .defaultDisplayImageOptions(AppConfig.defaultImageLoadOptions)
//                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
//                .imageDownloader(new BaseImageDownloader(context)) // default
//                .imageDecoder(new BaseImageDecoder()) // default
//                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
//                .writeDebugLogs()
                .build();
        ImageLoader.getInstance().init(config);
    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public long getTotalMemory() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);
            ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
            activityManager.getMemoryInfo(memoryInfo);
            return memoryInfo.totalMem;
        } else {
            return getTotalMemoryPre16();
        }
    }

    public long getTotalMemoryPre16() {
        String str1 = "/proc/meminfo";
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            str2 = localBufferedReader.readLine();//meminfo
            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }
            //total Memory
            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;
            localBufferedReader.close();
            return initial_memory;
        } catch (IOException e) {
            return -1;
        }

    }

    public int imageWidth() {
        return ImageUtils.beyondThreshold(totalMemory) ? ImageUtils.LARGE_IMG_WIDTH : ImageUtils.SMALL_IMG_WIDTH;
    }

    public int imageHeight() {
        return ImageUtils.beyondThreshold(totalMemory) ? ImageUtils.LARGE_IMG_HEIGHT : ImageUtils.SMALL_IMG_HEIGHT;
    }


    //=========userInfo

    private static final String ACCOUNT = "ACCOUNT";


    public static boolean isUpStream(Context ctx) {

        ResponseMcSigninBean bean = loadAccount(ctx);
        return bean.getIsUpstream();

    }
    public static void loginOut(Context ctx) {
        File dir = ctx.getFilesDir();
        String[] fileNameList = dir.list();
        for (String item : fileNameList) {
            File file = new File(dir, item);
            if (file.exists() && !file.isDirectory()) {
                file.delete();
            }
        }

//        AccountInfo.setNeedPush(ctx, true);
    }


    public static void saveAccount(Context ctx, ResponseMcSigninBean data) {
        File file = new File(ctx.getFilesDir(), ACCOUNT);
        if (file.exists()) {
            file.delete();
        }

        try {
            ObjectOutputStream oos = new ObjectOutputStream(ctx.openFileOutput(ACCOUNT, Context.MODE_PRIVATE));
            oos.writeObject(data);
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ResponseMcSigninBean loadAccount(Context ctx) {
        ResponseMcSigninBean data = null;
        File file = new File(ctx.getFilesDir(), ACCOUNT);
        if (file.exists()) {
            try {
                ObjectInputStream ois = new ObjectInputStream(ctx.openFileInput(ACCOUNT));
                data = (ResponseMcSigninBean) ois.readObject();
                ois.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (data == null) {
            data = new ResponseMcSigninBean();
        }

        return data;
    }

    public static boolean isLogin(Context ctx) {
        File file = new File(ctx.getFilesDir(), ACCOUNT);
        return file.exists();
    }


}
